package com.ivory.valley.common;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;



import net.sf.json.JSONObject;

public class JsapiTicket {
	public final static String Access_Token = null;
	public static String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
	public static void main(String[] args) {
		//String appid = "wx7491574828fade87";
		//String secret = "41541e965951426dc10de89f5fd80332";
		String access_token = "XhNsXKm6F6K7DlaEhCBOaytBtb6z66P9NF2gO7LaJvcCpECXZy6f2Tdio7kbmBiDG7tIOBky25cKt8bB8jQD7G4f38QJVE9ef_OWqQb4-rxs9XBrFw-GqptfhULnD9hwFLOcAHABHK";
		httpGetTicket(access_token,url);
	}

	public static void httpGetTicket(String access_token,String url){
		url = url.replaceAll("ACCESS_TOKEN", access_token);
		String ticket = null;
	    String expiresIn = null;
		try {
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET");
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			String message = new String(jsonBytes,"UTF-8");
			JSONObject json = JSONObject.fromObject(message);
			ticket = json.getString("ticket");
			expiresIn = json.getString("expires_in");
			//更新ticket到全局
			SignAttr.Jsapi_Ticket = ticket;
			SignAttr.Jsapi_Ticket_Time = System.currentTimeMillis()/1000;
			SignAttr.Jsapi_Ticket_ExpiresIn = Integer.valueOf(expiresIn);
			
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
